import ReconnectingWebSocket from 'reconnecting-websocket';
import { socketUrl } from './config';

const WebSocket = (topic, success, closed, fail) => {
    // WebSocket
    const rws = new ReconnectingWebSocket(socketUrl);
    rws.addEventListener('open', () => {
        rws.send('kgtdata');
    });
    rws.addEventListener('message', res => {
        const data = JSON.parse(res.data);
        data.topic === topic && success && success(data, rws);
    });
    rws.addEventListener('close', msg => {
        console.log(topic + ':close');
        closed && closed(msg);
    });
    rws.addEventListener('error', error => {
        fail && fail(error);
    });
    window.onbeforeunload = () => {
        rws.close();
    }
}

export default WebSocket